#define _CRT_SECURE_NO_WARNINGS 1

#include"seqlist.h"

void SLInit(SL* ps)
{
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}

void SLDestory(SL* ps)
{
	if (ps->a)
		free(ps->a);
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}

void SLPrint(SL* ps) 
{
	for (size_t i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

void SLCheckCapacity(SL* ps)
{
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SLdatatype* tmp = (SLdatatype*)realloc(ps->a, newcapacity * sizeof(SLdatatype));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return 1;
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}
}

bool SLEmpty(SL* ps)
{
	assert(ps);
	return ps->size == 0;
}

void SLPushBack(SL* ps, SLdatatype x)
{
	assert(ps);

	SLCheckCapacity(ps);
	ps->a[ps->size++] = x;
}

void SLPushfront(SL* ps, SLdatatype x)
{
	assert(ps);

	SLCheckCapacity(ps);
	for (int i = ps->size; i > 0; i--)
	{
		ps->a[i] = ps->a[i - 1];
	}
	ps->a[0] = x;
	ps->size++;
}

void SLPopBack(SL* ps)
{
	assert(ps);
	assert(!SLEmpty(ps));

	ps->size--;
}

void SLPopfront(SL* ps)
{
	assert(ps);
	assert(!SLEmpty(ps));

	for (int i = 0; i < ps->size-1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->size--;
}

void SLInsert(SL* ps, int pos, SLdatatype x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	SLCheckCapacity(ps);
	for (int i = ps->size; i > pos; i--)
	{
		ps->a[i] = ps->a[i - 1];
	}
	ps->a[pos] = x;
	ps->size++;
}

void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(!SLEmpty(ps));
	assert(pos >= 0 && pos < ps->size);

	for (int i = pos; i < ps->size - 1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->size--;
}

bool SLFind(SL* ps, SLdatatype x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
			return true;
	}
	return false;
}